import Singleton from "../Base/Singleton";
import { EntityTypeEnum } from "../Common";
import { Node, instantiate } from "cc";
import DataManager from "./DataManager";

export default class ObjectPoolManager extends Singleton {
  static get Instance() {
    return super.GetInstance<ObjectPoolManager>();
  }

  private objectPool: Node;
  private map: Map<EntityTypeEnum, Node[]> = new Map<EntityTypeEnum, Node[]>();

  get(type: EntityTypeEnum) {
    if (!this.objectPool) {
      this.objectPool = new Node("ObjectPool");
      this.objectPool.setParent(DataManager.Instance.stage);
    }

    if (!this.map.has(type)) {
      this.map.set(type, []);
      const container = new Node(type + "Pool");
      container.setParent(this.objectPool);
    }

    const nodes = this.map.get(type);
    if (!nodes.length) {
      let thisPref = DataManager.Instance.mapPrefab.get(type);
      let newNode = instantiate(thisPref);
      newNode.name = type;
      newNode.setParent(this.objectPool.getChildByName(type + "Pool"));
      return newNode;
    }

    let node = nodes.shift();
    node.active = true;
    return node;
  }

  ret(node: Node) {
    node.active = false;

    this.map.get(node.name as EntityTypeEnum).push(node);
  }
}
